var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var HIDE = 'hide';
var LAST = 'last';
var GRAY = 'gray';
var INFO = 'info';
var JOIN = 'join';
var CDKEYS = 'cdKeys';
Object.defineProperty(Array.prototype, LAST, {
    get: function () {
        return this.length ? this[this.length - 1] : -1;
    }
});
var Utils = /** @class */ (function () {
    function Utils() {
        /**
         * @param name 获取url中参数函数
         */
        this.getParameterByNameMap = null;
        Utils._ins = this;
    }
    Object.defineProperty(Utils, "instance", {
        get: function () {
            return this._ins ? this._ins : new Utils;
        },
        enumerable: true,
        configurable: true
    });
    Utils.prototype.getParameterByName = function (name) {
        var _this = this;
        if (!this.getParameterByNameMap) {
            this.getParameterByNameMap = {};
            var interrogationIndex = location.href.indexOf('?') + 1;
            var str = interrogationIndex === 0 ? '' : location.href.slice(interrogationIndex);
            if (str) {
                var arr = str.split(/&|%26/);
                arr.forEach(function (item) {
                    var arr = item.split(/=|%3D/);
                    var key = arr[0];
                    var val = arr[1];
                    _this.getParameterByNameMap[key] = val;
                });
            }
        }
        var params = this.getParameterByNameMap;
        return params.hasOwnProperty(name) ? params[name] : null;
    };
    Object.defineProperty(Utils.prototype, "random", {
        /**
         * 获取随机数
         */
        get: function () {
            return Math.random() * 1000;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * 获取dom元素的相对浏览器顶部的高度
     */
    Utils.prototype.getElementTop = function (element) {
        var actualTop = element.offsetTop;
        var current = element.offsetParent;
        while (current !== null) {
            actualTop += current.offsetTop;
            current = current.offsetParent;
        }
        return actualTop;
    };
    return Utils;
}());
var Store = /** @class */ (function () {
    function Store() {
        /**
         * 前缀尺寸
         */
        this.size = 6;
        Store._ins = this;
        this.pre = window.md5.md5(window.app + '', 32).slice(0, this.size);
        this.storage = localStorage;
    }
    Object.defineProperty(Store, "instance", {
        get: function () {
            return this._ins ? this._ins : new Store;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * 获取活动前缀
     */
    Store.prototype.getPre = function () {
        return this.pre;
    };
    Store.prototype.getStore = function () {
        var _ = {};
        for (var allName in this.storage) {
            var pre = allName.slice(0, this.size);
            if (pre === this.pre) {
                var name = allName.slice(this.size);
                _[name] = this.getItem(name);
            }
        }
        return _;
    };
    Store.prototype.setItem = function (key, value) {
        key = this.pre + key;
        value = JSON.stringify({
            value: value
        });
        this.storage.setItem(key, value);
    };
    Store.prototype.getItem = function (key) {
        key = this.pre + key;
        if (this.storage.hasOwnProperty(key)) {
            return JSON.parse(this.storage.getItem(key)).value;
        }
        return null;
    };
    Store.prototype.clear = function () {
        for (var allName in this.storage) {
            var pre = allName.slice(0, this.size);
            if (pre === this.pre) {
                delete this.storage[allName];
            }
        }
    };
    return Store;
}());
var Events = /** @class */ (function () {
    function Events() {
        this._infos = [];
        this._historys = [];
    }
    Object.defineProperty(Events.prototype, "actId", {
        get: function () {
            return Events._actId[this._eventIndex];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Events.prototype, "rewardId", {
        get: function () {
            return Events._rewardIds[this._eventIndex];
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Events.prototype, "info", {
        get: function () {
            return this._infos[this._eventIndex];
        },
        set: function (info) {
            this._infos[this._eventIndex] = info;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Events.prototype, "history", {
        get: function () {
            return this._historys[this._eventIndex];
        },
        set: function (history) {
            this._historys[this._eventIndex] = history;
        },
        enumerable: true,
        configurable: true
    });
    Events.groupId = '5adf1ac790bf7f1a14bf80d8';
    Events._actId = [
        '5ae1c04b90bf7f1a14bf830f',
        '5ae1c08f90bf7f1a14bf8310',
        '5ae2e0b590bf7f1a14bf837e'
    ];
    Events._rewardIds = [
        [
            '5aeaf75390bf7f1a14bf84f8'
        ],
        [
            '5ae2e08290bf7f1a14bf837d',
            '5ae30b9c90bf7f1a14bf838e',
            '5ae30c1a90bf7f1a14bf8395'
        ],
        [
            '5aeaf82b90bf7f1a14bf90bd',
            '5aeaf88090bf7f1a14bf90c0',
            '5aeaf8dd90bf7f1a14bf90c3',
            '5aeaf94b90bf7f1a14bf90c8',
            '5aeaf98f90bf7f1a14bf90cb',
            '5aeaf9db90bf7f1a14bf90ce',
            '5aeafa4190bf7f1a14bf90db'
        ]
    ];
    return Events;
}());
var Event3 = /** @class */ (function (_super) {
    __extends(Event3, _super);
    function Event3() {
        var _this = _super.call(this) || this;
        /**
         * 活动键值
         */
        _this._eventIndex = 2;
        Event3._ins = _this;
        return _this;
    }
    Object.defineProperty(Event3, "instance", {
        get: function () {
            return this._ins ? this._ins : new Event3;
        },
        enumerable: true,
        configurable: true
    });
    Event3.prototype.queryEvent = function (tag, params) {
        var _this = this;
        var datas = {
            groupId: Events.groupId,
            actId: this.actId,
            token: Config.userInfo.token
        };
        switch (tag) {
            case INFO:
                datas.rewardId = this.rewardId.last;
                break;
            case JOIN:
                datas.step = params.step;
                datas.rewardId = this.rewardId[params.step];
                break;
        }
        return Http.instance.getActivity(tag, datas).then(function (data) {
            if (data.code === 200) {
                var is200 = data.code === 200;
                switch (tag) {
                    case INFO:
                        _this.info = is200 ? data.state : null;
                        break;
                    case CDKEYS:
                        _this.history = is200 ? data.state : [];
                }
            }
            return data;
        });
    };
    return Event3;
}(Events));
var Event2 = /** @class */ (function (_super) {
    __extends(Event2, _super);
    function Event2() {
        var _this = _super.call(this) || this;
        /**
         * 活动键值
         */
        _this._eventIndex = 1;
        /**
         * 当前期数 0,1,2
         */
        _this._issue = null;
        _this._systemTicket = [];
        _this._userTicket = [];
        _this.gotRewardMap = {
            0: false,
            1: false,
            2: false
        };
        Event2._ins = _this;
        return _this;
    }
    Object.defineProperty(Event2, "instance", {
        get: function () {
            return this._ins ? this._ins : new Event2;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Event2.prototype, "systemTicket", {
        get: function () {
            return this._systemTicket;
        },
        enumerable: true,
        configurable: true
    });
    Event2.prototype.infoInit = function (state) {
        var _this = this;
        this.info = state;
        this.setUserTicket(state.UserTicket);
        var systemTicket = state.SystemTicket;
        var keys = Object.keys(systemTicket);
        if (keys.length) {
            keys.forEach(function (step) {
                _this._systemTicket[Number(step)] = Array.from(systemTicket[step]).map(function (index) { return Number(index); });
            });
            var issue = Number(keys.last) + 1;
            this._issue = Math.min(issue, 2);
        }
        else {
            this._issue = 0;
        }
        return this._issue;
    };
    Object.defineProperty(Event2.prototype, "userTicket", {
        get: function () {
            return this._userTicket;
        },
        enumerable: true,
        configurable: true
    });
    Event2.prototype.setUserTicket = function (userTicket) {
        var _this = this;
        var keys = Object.keys(userTicket);
        if (keys.length) {
            keys.forEach(function (step) {
                _this._userTicket[Number(step)] = Array.from(userTicket[step]).map(function (index) { return Number(index); });
            });
        }
    };
    Object.defineProperty(Event2.prototype, "issue", {
        get: function () {
            return this._issue;
        },
        enumerable: true,
        configurable: true
    });
    Event2.prototype.queryEvent = function (tag, params) {
        var _this = this;
        var datas = {
            groupId: Events.groupId,
            actId: this.actId,
            token: Config.userInfo.token
        };
        switch (tag) {
            case INFO:
                datas.rewardId = this.rewardId.last;
                break;
            case JOIN:
                datas.step = params.step;
                if (params.ticket)
                    datas.ticket = params.ticket;
                if (params.rewardId)
                    datas.rewardId = params.rewardId;
                break;
        }
        return Http.instance.getActivity(tag, datas).then(function (data) {
            var is200 = data.code === 200;
            switch (tag) {
                case INFO:
                    data.state.issue = is200 ? _this.infoInit(data.state) : 0;
                    _this.info = data.state;
                    break;
                case CDKEYS:
                    if (is200) {
                        _this.history = data.state;
                        if (_this.history.length) {
                            _this.history.forEach(function (item) {
                                var issue = item.extInfo.step;
                                _this.gotRewardMap[issue] = true;
                            });
                        }
                    }
                    else {
                        _this.history = [];
                    }
            }
            return data;
        });
    };
    return Event2;
}(Events));
var Event1 = /** @class */ (function (_super) {
    __extends(Event1, _super);
    function Event1() {
        var _this = _super.call(this) || this;
        /**
         * 活动键值
         */
        _this._eventIndex = 0;
        Event1._ins = _this;
        return _this;
    }
    Object.defineProperty(Event1, "instance", {
        get: function () {
            return this._ins ? this._ins : new Event1;
        },
        enumerable: true,
        configurable: true
    });
    Event1.prototype.queryEvent = function (tag, params) {
        var _this = this;
        var datas = {
            groupId: Events.groupId,
            actId: this.actId,
            token: Config.userInfo.token
        };
        switch (tag) {
            case INFO:
                datas.rewardId = this.rewardId.last;
                break;
            case JOIN:
                datas.rewardId = this.rewardId.last;
                break;
        }
        return Http.instance.getActivity(tag, datas).then(function (data) {
            var is200 = data.code === 200;
            switch (tag) {
                case INFO:
                    _this.info = is200 ? data.state : null;
                    break;
                case CDKEYS:
                    _this.history = is200 ? data.state : [];
            }
            return data;
        });
    };
    return Event1;
}(Events));
var Config = /** @class */ (function () {
    function Config() {
    }
    Config.appId = 10092;
    Config.fbId = '1088475561284955';
    Config.version = 'de';
    Config.fbRedirectUrl = (function () {
        return window['isMobile'] ? 'http://pmfr.pocketgamesol.com/activity/20180516/mobile/index.html' : 'http://pmfr.pocketgamesol.com/activity/20180516/index.html';
    })();
    // 'http://172.16.3.209:8018/kdyg3ds-fr/activity/' + window.app // 'http://127.0.0.1:9000' 
    Config.zoneMap = {};
    Config.zoneList = null;
    Config.roleList = [];
    Config.loginInfo = null;
    Config.userInfo = null;
    Config.roleInfo = null;
    Config.zoneInfo = null;
    return Config;
}());
var Http = /** @class */ (function () {
    function Http() {
        /**
          * 服务器ip地址
          */
        this.serverAdress = 'https://activity.pocketgamesol.com/'; //'http://10.10.3.144:8081'
        /**
         * 平台登录
         */
        this.pfLoginUrl = this.serverAdress + '/user/sdk/login';
        /**
         * facebookId 登录路径
         */
        this.fbLoginUrl = this.serverAdress + '/user/fb/login';
        /**
         * 获取区服 地址
         */
        this.zonesUrl = this.serverAdress + '/user/sdk/zones';
        /**
         * 获取角色 地址
         */
        this.roleUrl = this.serverAdress + '/user/player/list';
        Http._ins = this;
    }
    Object.defineProperty(Http, "instance", {
        get: function () {
            return this._ins ? this._ins : new Http;
        },
        enumerable: true,
        configurable: true
    });
    Http.prototype.fbLogin = function (code) {
        return $.ajax({
            type: 'GET',
            url: this.fbLoginUrl,
            data: {
                clientId: Config.appId,
                redirectUrl: Config.fbRedirectUrl,
                code: code
            }
        });
    };
    Http.prototype.pfLogin = function (data) {
        return $.ajax({
            type: 'GET',
            url: this.pfLoginUrl,
            data: data
        });
    };
    Http.prototype.getZones = function () {
        return $.ajax({
            type: 'GET',
            url: this.zonesUrl,
            data: {
                appId: Config.appId,
                token: Store.instance.getItem('token')
            }
        });
    };
    Http.prototype.getRole = function (data) {
        return $.ajax({
            type: 'GET',
            url: this.roleUrl,
            data: data
        });
    };
    Http.prototype.getActivity = function (path, data) {
        var promise = $.Deferred();
        $.ajax({
            type: 'GET',
            url: this.serverAdress + '/activity/' + path,
            data: data
        }).then(function (data) {
            promise.resolve({
                code: data.code,
                state: data.state
            });
        });
        return promise;
    };
    return Http;
}());
var Login = /** @class */ (function () {
    function Login() {
        /**
         * 到期时间 30分钟
         */
        this.expire = 60 * 60 * 1000 * .5;
        this._isLogin = false;
        this._isRole = false;
        Login._ins = this;
    }
    Object.defineProperty(Login, "instance", {
        get: function () {
            return this._ins ? this._ins : new Login;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * 判断是否已登录
     */
    Login.prototype.isLogin = function () {
        Config.userInfo = Store.instance.getItem('userInfo');
        if (Config.userInfo) {
            var _a = Config.userInfo, userId = _a.userId, token = _a.token, activetime = _a.activetime;
            if (userId && token) {
                var active = new Date().getTime() - this.expire;
                if (activetime && active < activetime * 1) {
                    return true;
                }
                else {
                    Store.instance.clear();
                }
            }
        }
        return false;
    };
    /**
     * 是否选择了角色
     */
    Login.prototype.isRole = function () {
        Config.zoneInfo = Store.instance.getItem('zoneInfo');
        Config.roleInfo = Store.instance.getItem('roleInfo');
        if (Config.zoneInfo && Config.roleInfo) {
            return true;
        }
        return false;
    };
    Login.prototype.checkFbLogin = function () {
        var fbCode = Utils.instance.getParameterByName('code');
        if (!fbCode) {
            return false;
        }
        var promise = $.Deferred();
        Http.instance.fbLogin(fbCode).then(function (data) {
            promise.resolve(data);
        }).fail(function (err) {
            promise.resolve({
                code: 400,
                state: err
            });
        });
        return promise;
    };
    /**
     * fb登录
     */
    Login.prototype.fbLogin = function () {
        var loginUrl = "//www.facebook.com/v2.6/dialog/oauth?client_id=" + Config.fbId + "&redirect_uri=" + encodeURIComponent(Config.fbRedirectUrl) + "&r=" + Utils.instance.random;
        location.href = loginUrl;
    };
    /**
     * 平台登录
     */
    Login.prototype.pfLogin = function () {
        var promise = $.Deferred();
        var userName = window.username.value; // = 'Qiong@9266.com'
        var password = window.password.value; // = 'qqqqqq'
        password = window.md5.md5(password, 32);
        var version = Config.version;
        if (!userName || !password) {
            promise.resolve({
                code: 400,
                state: window.translation.loginInfoErr
            });
        }
        else {
            Http.instance.pfLogin({
                userName: userName,
                password: password,
                version: version
            }).then(function (data) {
                promise.resolve(data);
            }).fail(function (err) {
                promise.resolve({
                    code: 400,
                    state: err
                });
            });
        }
        return promise;
    };
    return Login;
}());
var Dom = /** @class */ (function () {
    function Dom() {
    }
    Dom.logo = $('.logo');
    Dom.loading = $('.loading');
    Dom.mask = $('.mask');
    Dom.connect = $('.header .btn.gold');
    Dom.logged = $('.header .logged');
    Dom.logout = $('.header .logout');
    // event1
    Dom.event1Btn = $('.event1 .btn');
    // event2
    Dom.event2Overview = $('.event2 .overview');
    Dom.event2Record = $('.event2 .record');
    Dom.event2TimebarItems = $('.event2 .timebar .item');
    Dom.event2PokemonsItems = $('.event2 .pokemons .item');
    Dom.event2PokemonsItemsG = Dom.event2PokemonsItems.find('.poke-g');
    Dom.event2PokemonsItemsL = Dom.event2PokemonsItems.find('.poke-l');
    Dom.event2PokemonsItemsC = Dom.event2PokemonsItems.find('.poke-c');
    Dom.event2PokemonsItemsGL = Dom.event2PokemonsItems.find('.poke-g, .poke-l');
    Dom.event2Submit = $('.event2 .btn');
    // event3
    Dom.event3Card = $('.event3 .card');
    Dom.event3CardBtns = $('.event3 .card .btn');
    // pop
    Dom.x = $('.x');
    Dom.popLogin = $('.pop.login');
    Dom.popCtn = $('.pop.ctn');
    Dom.ctnBox = $('.pop.ctn .ctn');
    Dom.loginBtn = $('.pop .login .btns');
    Dom.popOverview = $('.pop.overview');
    Dom.popServer = $('.pop.server');
    Dom.$server = $('#server');
    Dom.$role = $('#role');
    Dom.serverItem = $('.pop.server .item.server');
    Dom.roleItem = $('.pop.server .item.role');
    Dom.popServerConfirm = $('.pop.server .btn');
    return Dom;
}());
var App;
(function (App) {
    var Main = /** @class */ (function () {
        function Main() {
            this.activePokeItem = [];
            this.activePokeItemMap = {};
            this.event1CanClick = true;
            this.event2CanClick = true;
            this.event3CanClick = true;
            this.queue = [];
            this.canChage = true;
            this.zoneId = null;
            Main._ins = this;
        }
        Object.defineProperty(Main, "instance", {
            get: function () {
                return this._ins ? this._ins : new Main;
            },
            enumerable: true,
            configurable: true
        });
        Main.prototype.init = function () {
            var _this = this;
            window.modules = {
                utils: Utils.instance,
                dom: Dom
            };
            this.bindEvents();
            this.setZones();
            this.handlerLogin();
            this.handlerRole();
            var promise = Login.instance.checkFbLogin();
            promise && promise.then(function (data) {
                _this.dataHandler(data, function () {
                    _this.loginSucc(data);
                }, function () {
                    location.href = location.origin + location.pathname;
                    return 'stop';
                });
            });
        };
        /**
         * 初始化区服信息
         */
        Main.prototype.setZones = function () {
            var _this = this;
            Http.instance.getZones().then(function (data) {
                Config.zoneList = data.state;
                _this.dataHandler(data, function () {
                    var str = "<option value=\"0\">S\u00E9lectionnez serveur</option>";
                    Config.zoneList.forEach(function (item, i) {
                        var localName = item.localName, mainGameZoneId = item.mainGameZoneId;
                        Config.zoneMap[mainGameZoneId] = i;
                        str += "<option value=\"" + mainGameZoneId + "\">" + localName + "</option>";
                    });
                    Dom.$server.html(str);
                });
            });
        };
        Main.prototype.dataHandler = function (data, succFn, failFn) {
            var code = data.code, state = data.state;
            if (!code) {
                Store.instance.clear();
                location.reload();
                return;
            }
            if (code === 200) {
                succFn && succFn();
            }
            else if (code === 300) { // not login
                Store.instance.clear();
                Dom.popServerConfirm.data('role', false);
                Dom.$role.html('');
                window.server.value = '0';
                Login.instance._isLogin = Login.instance._isRole = false;
                this.loginCheck();
            }
            else {
                var flag = true;
                failFn && (flag = failFn());
                if (flag !== 'stop') {
                    var statement;
                    statement = window.translation.codes[code] || (code + ', ' + state);
                    this.showErr(statement);
                }
            }
        };
        Main.prototype.showErr = function (message, config) {
            if (config && config.align) {
                Dom.ctnBox.css({ 'text-align': config.align });
            }
            else {
                Dom.ctnBox.css({ 'text-align': 'center' });
            }
            Dom.ctnBox.html(message);
            this.showQueue(Dom.popCtn);
        };
        Main.prototype.consoleLog = function (cs, tag) {
            tag ? console.log(tag, cs) : console.log(cs);
        };
        Main.prototype.userInfoRender = function () {
            Login.instance._isLogin = true;
            Dom.connect.addClass(HIDE);
            Dom.logged.removeClass(HIDE);
            Dom.logged.find('.username span').html(Config.userInfo.userName);
        };
        Main.prototype.roleInfoRender = function () {
            var _this = this;
            Login.instance._isRole = true;
            Dom.logged.find('.zonename, .rolename').removeClass(HIDE);
            Dom.logged.find('.zonename span').html(Config.zoneInfo.localName);
            Dom.logged.find('.rolename span').html(Config.roleInfo.playerName);
            { // event1
                $.when(Event1.instance.queryEvent(INFO).done(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event1 INFO'), _this.consoleLog.bind(_this, data.state, 'Event1 INFO'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                }), Event1.instance.queryEvent(CDKEYS).then(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event1 CDKEYS'), _this.consoleLog.bind(_this, data.state, 'Event1 CDKEYS'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                })).always(function (data) {
                    if (Event1.instance.history.length) {
                        Dom.event1Btn.data('state', 'over');
                        Dom.event1Btn.attr('class', 'btn gold');
                        Dom.event1Btn.text(window.translation.achieved);
                    }
                    else {
                        Dom.event1Btn.data('state', 'reward');
                        Dom.event1Btn.attr('class', 'btn gold');
                        Dom.event1Btn.text(window.translation.get);
                    }
                });
            }
            { // event2
                $.when(Event2.instance.queryEvent(INFO).done(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event2 INFO'), _this.consoleLog.bind(_this, data.state, 'Event2 INFO'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                }), Event2.instance.queryEvent(CDKEYS).then(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event2 CDKEYS'), _this.consoleLog.bind(_this, data.state, 'Event2 CDKEYS'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                })).always(function (data) {
                    _this.event2Render(Event2.instance.info.issue);
                });
            }
            { // event3
                $.when(Event3.instance.queryEvent(INFO).done(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event3 INFO'), _this.consoleLog.bind(_this, data.state, 'Event3 INFO'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                }), Event3.instance.queryEvent(CDKEYS).then(function (data) {
                    _this.dataHandler(data, _this.consoleLog.bind(_this, data.state, 'Event3 CDKEYS'), _this.consoleLog.bind(_this, data.state, 'Event3 CDKEYS'));
                }).fail(function (err) {
                    console.error(err);
                    _this.showErr(err);
                })).always(function (data) {
                    if (Event3.instance.info.gameLogin.length) { // 可以领奖
                        if (Event3.instance.history.length) {
                            var rws = {};
                            Event3.instance.history.forEach(function (item, i) {
                                rws[item.rewardId] = true;
                            });
                            Event3.instance.info.gameLogin.forEach(function (item, i) {
                                var btn = Dom.event3CardBtns.eq(i);
                                if (!rws.hasOwnProperty(Event3.instance.rewardId[i])) {
                                    btn.attr('class', 'btn gold');
                                    btn.data('state', 'reward');
                                    btn.text(window.translation.get);
                                }
                                else {
                                    btn.attr('class', 'btn gold');
                                    btn.data('state', 'over');
                                    btn.text(window.translation.achieved);
                                }
                            });
                        }
                        else {
                            Event3.instance.info.gameLogin.forEach(function (item, i) {
                                var btn = Dom.event3CardBtns.eq(i);
                                btn.attr('class', 'btn gold');
                                btn.data('state', 'reward');
                            });
                        }
                    }
                });
            }
        };
        Main.prototype.handlerLogin = function (flag) {
            if (flag) {
                this.userInfoRender();
            }
            else {
                if (Login.instance.isLogin()) {
                    this.userInfoRender();
                }
                else {
                    Dom.connect.removeClass(HIDE);
                }
            }
        };
        Main.prototype.handlerRole = function (flag) {
            if (flag) {
                this.roleInfoRender();
            }
            else {
                if (Login.instance.isRole()) {
                    this.roleInfoRender();
                }
            }
        };
        Main.prototype.showQueue = function (dom) {
            this.queue.push(dom);
            dom.removeClass(HIDE);
            var length = this.queue.length;
            if (length === 1) {
                Dom.mask.removeClass(HIDE);
            }
            else {
                this.queue[length - 2].addClass('sink');
            }
        };
        Main.prototype.removeQueue = function () {
            if (this.queue.length) {
                var hide = this.queue.pop();
                var length = this.queue.length;
                hide.addClass('hide');
                if (!length) {
                    Dom.mask.addClass(HIDE);
                }
                else {
                    this.queue[length - 1].removeClass('sink');
                }
            }
        };
        Main.prototype.serverChange = function () {
            var _this = this;
            if (Config.roleList[window.server.value]) {
                Dom.$role.html(Config.roleList[window.server.value][0].playerName);
                Dom.popServerConfirm.data('role', true);
                return;
            }
            if (this.canChage) {
                this.canChage = false;
                this.zoneId = window.server.value;
                Dom.$role.html(window.translation.querying);
                Dom.popServerConfirm.data('role', false);
                Http.instance.getRole({
                    appId: Config.appId,
                    gameZoneId: this.zoneId,
                    token: Config.userInfo.token
                }).then(function (data) {
                    // dom
                    Dom.$role.html('');
                    _this.canChage = true;
                    if (data.state.length) {
                        Config.roleList[_this.zoneId] = data.state;
                    }
                    if (!Config.roleList[_this.zoneId]) {
                        Dom.$role.html(window.translation.noRole);
                        Dom.popServerConfirm.data('role', false);
                        return;
                    }
                    _this.dataHandler(data, function () {
                        if (_this.zoneId === window.server.value) {
                            Dom.$role.html(Config.roleList[_this.zoneId][0].playerName);
                            Dom.popServerConfirm.data('role', true);
                        }
                    });
                    if (_this.zoneId !== window.server.value) {
                        _this.serverChange();
                    }
                }).fail(function (err) {
                    _this.showErr(window.translation.unknown);
                    _this.canChage = true;
                    if (_this.zoneId !== window.server.value) {
                        _this.serverChange();
                    }
                });
            }
        };
        Main.prototype.bindEvents = function () {
            var _this = this;
            Dom.loading.addClass('loader');
            Dom.logo.click(function () {
                window.open('https://www.facebook.com/TrainerBattle/');
            });
            Dom.connect.click(function () {
                _this.showQueue(Dom.popLogin);
            });
            Dom.x.click(function () {
                _this.removeQueue();
            });
            Dom.popServerConfirm.click(function (e) {
                if (!Dom.popServerConfirm.data('role'))
                    return;
                Config.roleInfo = Config.roleList[window.server.value][0];
                Config.zoneInfo = Config.zoneList[Config.zoneMap[window.server.value]];
                Store.instance.setItem('roleInfo', Config.roleInfo);
                Store.instance.setItem('zoneInfo', Config.zoneInfo);
                _this.removeQueue();
                _this.handlerRole(true);
            });
            Dom.logout.click(function () {
                Store.instance.clear();
                location.reload();
            });
            Dom.$server.change(function () {
                _this.serverChange();
            });
            Dom.loginBtn.on('click', '.btn', function (e) {
                var target = $(e.target);
                var isFb = target.hasClass('fb');
                if (isFb) {
                    Login.instance.fbLogin();
                }
                else {
                    Login.instance.pfLogin().then(function (data) {
                        _this.dataHandler(data, function () {
                            _this.loginSucc(data);
                        });
                    });
                }
            });
            Dom.event1Btn.click(function () {
                if (!_this.loginCheck())
                    return;
                var state = Dom.event1Btn.data('state');
                if (_this.event1CanClick && state) {
                    var info = Event1.instance.info;
                    if (info && info.joinTime.sumTime !== 0) {
                        _this.event1CanClick = false;
                        Event1.instance.queryEvent(JOIN).then(function (data) {
                            _this.dataHandler(data, function () {
                                Event1.instance.info = {
                                    joinTime: {
                                        sumTime: 0
                                    }
                                };
                                Event1.instance.history = [{
                                        cdKeys: data.state.cdKeys
                                    }];
                                Dom.event1Btn.data('state', 'over');
                                Dom.event1Btn.attr('class', 'btn gold');
                                Dom.event1Btn.text(window.translation.achieved);
                                _this.showErr(data.state.cdKeys);
                            }, function () {
                                _this.showErr(window.translation.event1_not_achieve);
                                return 'stop';
                            });
                            _this.event1CanClick = true;
                        }).fail(function (err) {
                            _this.event1CanClick = true;
                            _this.showErr(window.translation.noRole);
                        });
                    }
                    else {
                        var history = Event1.instance.history.last;
                        _this.showErr(history.cdKeys);
                    }
                }
            });
            Dom.event3Card.on('click', '.btn', function (e) {
                if (!_this.loginCheck())
                    return;
                var item = $(e.target);
                var state = item.data('state');
                if (state) {
                    switch (state) {
                        case 'reward':
                            var step = Number(e.target.dataset.index);
                            if (_this.event3CanClick) {
                                _this.event3CanClick = false;
                                Event3.instance.queryEvent(JOIN, { step: step }).then(function (data) {
                                    _this.dataHandler(data, function () {
                                        _this.showErr(window.translation.emailOk);
                                        var btn = Dom.event3CardBtns.eq(step);
                                        btn.data('state', 'over');
                                        btn.text(window.translation.achieved);
                                    });
                                }).done(function () {
                                    _this.event3CanClick = true;
                                }).fail(function (err) {
                                    _this.event3CanClick = true;
                                    console.error(err);
                                    _this.showErr(window.translation.unknown);
                                });
                            }
                            break;
                        case 'over':
                            _this.showErr(window.translation.emailOk);
                    }
                }
            });
            Dom.event2TimebarItems.click(function (e) {
                if (!_this.loginCheck())
                    return;
                var item = $(e.target);
                if (!item.hasClass('item'))
                    item = $(e.target).parents('.item');
                var index = item.index();
                if (index > Event2.instance.issue) {
                    _this.showErr(window.translation.notStart);
                }
                else {
                    _this.event2Render(index);
                }
            });
            Dom.event2PokemonsItemsGL.click(function (e) {
                if (!_this.loginCheck())
                    return;
                e.stopPropagation();
                if (_this.timebarIndex === Event2.instance.issue) {
                    var userInfo = Event2.instance.userTicket[_this.timebarIndex];
                    if (!userInfo) {
                        var item = $(e.target);
                        var index;
                        var isL = item.hasClass('poke-l');
                        var light, gray;
                        if (isL) {
                            light = item;
                            gray = item.siblings('.poke-g');
                            index = Dom.event2PokemonsItemsL.index(item);
                        }
                        else {
                            gray = item;
                            light = item.siblings('.poke-l');
                            index = Dom.event2PokemonsItemsG.index(item);
                        }
                        var prop = index + '';
                        var i;
                        if (_this.activePokeItemMap.hasOwnProperty(prop)) {
                            i = _this.activePokeItem.indexOf(index);
                            _this.activePokeItem.splice(i, 1);
                            var _a = _this.activePokeItemMap[prop], gray = _a.gray, index = _a.index, light = _a.light;
                            _this.pokeItemRender(light, gray);
                            delete _this.activePokeItemMap[prop];
                        }
                        else {
                            _this.pokeItemRender(gray, light);
                            _this.activePokeItemMap[prop] = { gray: gray, index: index, light: light };
                            i = _this.activePokeItem.indexOf(index);
                            if (i === -1) {
                                _this.activePokeItem.push(index);
                            }
                            if (_this.activePokeItem.length > 5) {
                                prop = _this.activePokeItem.shift() + '';
                                var _b = _this.activePokeItemMap[prop], gray = _b.gray, index = _b.index, light = _b.light;
                                _this.pokeItemRender(light, gray);
                                delete _this.activePokeItemMap[prop];
                            }
                        }
                    }
                }
            });
            Dom.event2Submit.click(function (e) {
                if (!_this.loginCheck())
                    return;
                var state = Dom.event2Submit.data('state');
                if (state) {
                    switch (state) {
                        case 'reward':
                            _this.getGuessReward();
                            break;
                        case 'join':
                            _this.joinGuessAct();
                            break;
                    }
                }
            });
            Dom.event2Overview.click(function (e) {
                _this.showQueue(Dom.popOverview);
            });
            Dom.event2Record.click(function (e) {
                if (!_this.loginCheck())
                    return;
                var str = '';
                for (var issue in Event2.instance.gotRewardMap) {
                    var isGet = Event2.instance.gotRewardMap[issue];
                    str += window.translation.issues[issue * 1];
                    str += isGet ? window.translation.congratulations : window.translation.pity;
                    str += '<br>';
                }
                _this.showErr(str, { align: 'left' });
            });
        };
        Main.prototype.loginSucc = function (data) {
            this.removeQueue();
            this.showQueue(Dom.popServer);
            Config.loginInfo = data.state;
            var activetime = new Date().getTime();
            var userInfo = Object.assign({ activetime: activetime }, Config.loginInfo);
            Config.userInfo = userInfo;
            Store.instance.setItem('userInfo', userInfo);
            this.handlerLogin(true);
        };
        Main.prototype.pokeItemRender = function (hide, show) {
            hide.addClass(HIDE);
            show.removeClass(HIDE);
        };
        Main.prototype.loginCheck = function () {
            if (!Login.instance._isLogin) {
                this.showQueue(Dom.popLogin);
                return false;
            }
            if (!Login.instance._isRole) {
                this.showQueue(Dom.popServer);
                return false;
            }
            return true;
        };
        Main.prototype.event2Render = function (index) {
            this.timebarIndex = index;
            this.timebarRender();
            this.crownRender();
            this.userChooseRender();
            this.event2SubmitRender();
        };
        Main.prototype.event2SubmitRender = function () {
            var systemInfo = Event2.instance.systemTicket[this.timebarIndex];
            var userInfo = Event2.instance.userTicket[this.timebarIndex];
            var isGotReward = Event2.instance.gotRewardMap[this.timebarIndex];
            var submit = Dom.event2Submit;
            if (systemInfo) {
                if (userInfo) {
                    var count = 0;
                    systemInfo.forEach(function (number) {
                        if (userInfo.indexOf(number) !== -1)
                            count++;
                    });
                    if (count >= 3 && !isGotReward) {
                        submit.attr('class', 'btn gold');
                        submit.data('state', 'reward');
                        submit.data('reward', count - 3);
                        submit.html(window.translation.reward);
                        return;
                    }
                }
                submit.attr('class', 'btn ed');
                submit.data('state', 'over');
                submit.html(window.translation.over);
            }
            else {
                if (userInfo) {
                    submit.attr('class', 'btn gold');
                    submit.data('state', 'over');
                    submit.html(window.translation.joinSucc);
                    return;
                }
                submit.attr('class', 'btn gold');
                submit.data('state', 'join');
                submit.html(window.translation.join);
            }
        };
        Main.prototype.getGuessReward = function () {
            var _this = this;
            if (this.event2CanClick) {
                this.event2CanClick = false;
                var step = this.timebarIndex;
                var submit = Dom.event2Submit;
                var rewardId = Event2.instance.rewardId[submit.data('reward')];
                Event2.instance.queryEvent(JOIN, { step: step, rewardId: rewardId }).then(function (data) {
                    _this.dataHandler(data, function () {
                        _this.showErr(window.translation.emailOk);
                        submit.attr('class', 'btn ed');
                        submit.data('state', 'over');
                        Event2.instance.gotRewardMap[step] = true;
                        submit.html(window.translation.over);
                    });
                }).done(function () {
                    _this.event2CanClick = true;
                }).fail(function (err) {
                    console.log(err);
                    _this.showErr(window.translation.unknown);
                    _this.event2CanClick = true;
                });
            }
        };
        Main.prototype.joinGuessAct = function () {
            var _this = this;
            var length = this.activePokeItem.length;
            if (length < 5) {
                this.showErr(window.translation.noFive);
                return;
            }
            if (this.event2CanClick) {
                this.event2CanClick = false;
                var submit = Dom.event2Submit;
                var ticket = this.activePokeItem.sort().join('');
                var step = this.timebarIndex;
                Event2.instance.queryEvent(JOIN, { ticket: ticket, step: step }).then(function (data) {
                    _this.dataHandler(data, function () {
                        _this.showErr(window.translation.joinSucc);
                        submit.attr('class', 'btn gold');
                        submit.data('state', 'reward');
                        submit.html(window.translation.reward);
                    }, function () {
                        if (data.code === 1005) {
                            _this.showErr(window.translation.wait);
                            return 'stop';
                        }
                    });
                }).done(function () {
                    _this.event2CanClick = true;
                }).fail(function (err) {
                    console.log(err);
                    _this.showErr(window.translation.unknown);
                    _this.event2CanClick = true;
                });
            }
        };
        Main.prototype.timebarRender = function () {
            Dom.event2TimebarItems.eq(this.timebarIndex).removeClass(GRAY).siblings().addClass(GRAY);
        };
        Main.prototype.crownRender = function () {
            var systemInfo = Event2.instance.systemTicket[this.timebarIndex];
            Dom.event2PokemonsItemsC.addClass(HIDE);
            if (systemInfo) {
                systemInfo.forEach(function (index) {
                    Dom.event2PokemonsItemsC.eq(index).removeClass(HIDE);
                });
            }
        };
        Main.prototype.userChooseRender = function () {
            var _this = this;
            var userInfo = Event2.instance.userTicket[this.timebarIndex];
            if (userInfo) {
                this.pokeItemRender(Dom.event2PokemonsItemsL, Dom.event2PokemonsItemsG);
                userInfo.forEach(function (index) {
                    _this.pokeItemRender(Dom.event2PokemonsItemsG.eq(index), Dom.event2PokemonsItemsL.eq(index));
                });
            }
            else {
                this.pokeItemRender(Dom.event2PokemonsItemsL, Dom.event2PokemonsItemsG);
                if (this.activePokeItem.length && this.timebarIndex === Event2.instance.issue) {
                    this.activePokeItem.forEach(function (index) {
                        _this.pokeItemRender(Dom.event2PokemonsItemsG.eq(index), Dom.event2PokemonsItemsL.eq(index));
                    });
                }
            }
        };
        return Main;
    }());
    App.Main = Main;
    var Button = /** @class */ (function () {
        function Button(btn, props, fn, mode) {
            if (mode === void 0) { mode = 0; }
            this.clickLimit = 500;
            this.button = btn;
            if (props && Object.prototype.toString.call(props) !== "[object Array]") {
                props = [props];
            }
            this.props = props || [];
            this.clickFn = fn || function () { };
            this.create();
            this.changeMdoe(mode);
        }
        Button.prototype.limit = function (clickLimit) {
            this.clickLimit = clickLimit;
        };
        Object.defineProperty(Button.prototype, "curProp", {
            get: function () {
                return this.props[this.mode];
            },
            enumerable: true,
            configurable: true
        });
        Button.prototype.initAction = function () {
            this.curProp.class = Button.defaultClassName.concat(this.curProp.class || []);
            this.button.attr('class', this.curProp.class.join(' '));
            if (this.curProp.text) {
                this.button.text(this.curProp.text);
            }
        };
        Button.prototype.create = function () {
            var _this = this;
            var len = Button.btnList.push(this.button);
            this.index = len - 1;
            this.button.data('index', this.index);
            this.button.click(function (e) {
                if (_this.clickLimit > 0) {
                    _this.clickFn.apply(_this, [e]);
                    setTimeout(_this.limit.bind(_this, _this.clickLimit), _this.clickLimit);
                    _this.clickLimit = -1;
                }
            });
        };
        Button.prototype.changeMdoe = function (mode) {
            this.mode = mode;
            this.initAction();
        };
        Button.defaultClassName = ["btn"];
        Button.btnList = [];
        return Button;
    }());
    App.Button = Button;
})(App || (App = {}));
if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
    window['isMobile'] = true;
}
App.Main.instance.init();
